/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.sdkj.dspservice.modules.sys.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.base.controller.BaseController;
import com.sdkj.dspservice.common.base.entity.BaseResult;
import com.sdkj.dspservice.common.config.Global;
import com.sdkj.dspservice.common.constant.HttpStatus;
import com.sdkj.dspservice.common.react.AntdProResult;
import com.sdkj.dspservice.common.utils.*;
import com.sdkj.dspservice.modules.sys.entity.Menu;
import com.sdkj.dspservice.modules.sys.entity.RoleMenu;
import com.sdkj.dspservice.modules.sys.entity.User;
import com.sdkj.dspservice.modules.sys.entity.UserRole;
import com.sdkj.dspservice.modules.sys.service.MenuService;
import com.sdkj.dspservice.modules.sys.service.RoleMenuService;
import com.sdkj.dspservice.modules.sys.service.UserRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单Controller
 *
 * @author tm
 * @version 2020-11-23
 */
@RestController
@RequestMapping(value = "${project-config.apiUrl}/${project-config.version}/sys/menu")
public class MenuController extends BaseController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleMenuService roleMenuService;

    @RequiresPermissions("sys:menu:view")
    @RequestMapping(value = "get")
    public AntdProResult get(String id) {
        AntdProResult result = new AntdProResult();
        if (StringUtils.isNotBlank(id)) {
            Menu menu = menuService.getById(id);
            if("0".equals(menu.getParentId())){
                menu.setParentId(null);
            }
            result.setData(menu);
        } else {
            result.error(HttpStatus.STATUS_400,
                    "id不能为空");
        }
        return result;
    }

    @RequiresPermissions("sys:menu:view")
    @RequestMapping(value = "list")
    public AntdProResult list(Menu menu) {
        AntdProResult result = new AntdProResult();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>(menu);
        queryWrapper.orderByAsc("sort");
        List<Menu> sourceList = menuService.list(queryWrapper);
        List<Menu> menuList = new ArrayList<>();
        Menu.makeTree(menuList, sourceList, Menu.getRootId(), true);
        menuList = TreeUtils.makeTree(menuList);
        result.success(menuList);
        return result;
    }

    @RequiresPermissions("sys:menu:edit")
    @RequestMapping(value = "save", produces = MediaType.APPLICATION_JSON_VALUE)
    public AntdProResult save(@Valid @RequestBody Menu menu) {
        AntdProResult result = new AntdProResult();
        menuService.saveOrUpdate(menu);
        return result;
    }

    @RequiresPermissions("sys:menu:edit")
    @RequestMapping(value = "remove")
    public BaseResult delete(String id, HttpServletResponse response) {
        BaseResult result = new BaseResult();
        if (StringUtils.isNotBlank(id)) {
            menuService.removeById(id);
        } else {
            response.setStatus(HttpStatus.STATUS_400);
            result.setErrorMessage("id不能为空");
        }
        return result;
    }

    /**
     * 获取树形数据
     *
     * @param extId
     * @param isShowHide
     * @param response
     * @return
     */
    @RequestMapping(value = "treeData")
    public AntdProResult treeData(Menu menu, @RequestParam(required = false) String extId, @RequestParam(required = false) String isShowHide, HttpServletResponse response) {
        AntdProResult result = new AntdProResult();
        List<Menu> resultList = new ArrayList<>();
        List<Menu> list = menuService.list(menu);
        for (int i = 0; i < list.size(); i++) {
            Menu e = list.get(i);
            // 判断extId是否为e的子菜单
            boolean isNotChild = extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1;
            // 如果extId是空，或者不为空且不为子菜单
            if (StringUtils.isBlank(extId) || isNotChild) {
                if (isShowHide != null && isShowHide.equals("0") && e.getIsShow().equals("0")) {
                    continue;
                }
                resultList.add(e);
            }
        }
        resultList = TreeUtils.makeTree(resultList);
        result.setData(ReactUtils.makeReactMenuData(resultList));
        return result;
    }

    /**
     * 获取当前用户可用菜单列表
     *
     * @return
     */
    @RequestMapping(value = "treeDataCurrentUser")
    public AntdProResult treeDataNowUser(){
        AntdProResult result = new AntdProResult();
        // 获取当前用户
        User user = UserUtils.getCurrentUser();
        // 获取当前用户角色
        UserRole searchUserRole = new UserRole();
        searchUserRole.setUserId(user.getId());
        List<UserRole> userRoleList = userRoleService.list(searchUserRole);
        if(CollectionsUtils.isNotEmpty(userRoleList)){
            // 获取角色idList
            List<String> roleIdList = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            // 根据角色idList获取菜单
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("role_id", roleIdList);
            List<RoleMenu> roleMenuList = roleMenuService.list(queryWrapper);
            // 获取所有角色的菜单
            if(CollectionsUtils.isNotEmpty(roleMenuList)){
                List<String> menuIdList = roleMenuList.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
                QueryWrapper<Menu> qw = new QueryWrapper();
                qw.in("id", menuIdList);
                qw.orderByAsc("sort");
                List<Menu> menuList = menuService.list(qw).stream().filter(menu -> Global.YES.equals(menu.getIsShow())).collect(Collectors.toList());
                result.success(ReactUtils.makeReactMenuData(TreeUtils.makeTree(menuList)));
            }
        }
        return result;
    }

}
